package com.vancouver.knows.ui.activity.citynews;

import java.io.File;
import java.util.ArrayList;
import java.util.List;

import android.app.Activity;
import android.app.ProgressDialog;
import android.content.ContentResolver;
import android.content.Intent;
import android.net.Uri;
import android.os.Bundle;
import android.os.Environment;
import android.support.v7.widget.Toolbar;
import android.text.TextUtils;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.ViewGroup;
import android.widget.EditText;
import android.widget.FrameLayout;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.RadioButton;
import android.widget.TextView;
import android.widget.Toast;
import butterknife.Bind;
import butterknife.ButterKnife;
import butterknife.OnCheckedChanged;
import butterknife.OnClick;

import com.pangu.service.ActionException;
import com.pangu.task.IResultReceiver;
import com.pangu.task.mark.ATaskMark;
import com.pangu.util.FileUtil;
import com.pangu.util.StringUtil;
import com.squareup.picasso.Picasso;
import com.vancouver.knows.R;
import com.vancouver.knows.ui.base.BaseActivity;
import com.vancouver.knows.ui.fragment.citynews.Crop;
import com.vancouver.knows.ui.fragment.citynews.SelectPicWindow;
import com.vancouver.knows.util.AppUtils;
import com.vancouver.knows.util.PhoConstants;
import com.vancouver.knows.business.bean.UserInfo;
import com.vancouver.knows.business.task.mark.UserPostArticleTaskMark;

/**
 * 发布界面
 * 
 * @author chenxunlin01
 * 
 */
public class AddPostActivity extends BaseActivity implements OnClickListener, IResultReceiver {

	@Bind(R.id.leftBtn)
	TextView leftBtn;
	@Bind(R.id.rightBtn)
	TextView rightBtn;
	@Bind(R.id.toobarTitle)
	TextView toolbarTitle;
	@Bind(R.id.title)
	EditText title;
	@Bind(R.id.content)
	EditText content;
	@Bind(R.id.addpostImgLayout)
	LinearLayout addpostImgLayout;
	@Bind(R.id.toolbar)
	Toolbar toolbar;
	@Bind(R.id.rootLayout)
	LinearLayout rootLayout;
	@Bind(R.id.irrigation)
	RadioButton irrigation;
	@Bind(R.id.secondhand)
	RadioButton secondhand;
	@Bind(R.id.seekhelp)
	RadioButton seekhelp;

	private String category;
	private List<String> imgs = new ArrayList<String>();
	private List<ViewHolder> viewHolders = new ArrayList<ViewHolder>();
	private static final String ADD_POST_BTN = "add_post_btn";
	private SelectPicWindow selectPicWindow;
	private String localFilePath;
	private ProgressDialog dialog;

	private String type;
	public static final String IRRIGATION = "irrigation";
	public static final String SECONDHAND = "secondhand";
	public static final String SEEKHELP = "seekhelp";

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.activity_addpost);
		init();
	}

	private void init() {
		Intent intent = getIntent();
		if (intent != null) {
			type = intent.getStringExtra("type");
		}

		if (!StringUtil.isEmptyString(type)) {
			if (IRRIGATION.equals(type)) {
				irrigation.setChecked(true);

			} else if (SECONDHAND.equals(type)) {
				secondhand.setChecked(true);

			} else if (SEEKHELP.endsWith(type)) {
				seekhelp.setChecked(true);
			}
		}

		toolbar.setTitle("");
		dialog = new ProgressDialog(this, R.style.MyAlertDialogStyle);
		dialog.setTitle("");
		dialog.setMessage(getResources().getString(R.string.report_loading));
		dialog.setIndeterminate(false);
		dialog.setCancelable(true);
		leftBtn.setText(R.string.left_btn);
		rightBtn.setText(R.string.right_btn);
		toolbarTitle.setText(R.string.addpost_title);
		selectPicWindow = new SelectPicWindow(this, this);
		updateAddPostImgLayout();
	}

	@OnClick(R.id.leftBtn)
	public void onLeftBtnClick() {
		finish();
	}

	@OnClick(R.id.rightBtn)
	public void onRightBtnClick() {
		String titleStr = title.getText().toString().trim();
		if (TextUtils.isEmpty(titleStr)) {
			Toast.makeText(this, R.string.addpost_no_title, 200).show();
			return;
		}
		String contentStr = content.getText().toString().trim();
		if (TextUtils.isEmpty(contentStr)) {
			Toast.makeText(this, R.string.addpost_no_content, 200).show();
			return;
		}

		if (TextUtils.isEmpty(category)) {
			Toast.makeText(this, R.string.addpost_no_category, 200).show();
			return;
		}

		UserPostArticleTaskMark aTaskMark = imContext.getBusinessModule().getTaskMarkPool()
				.getUserPostArticleTaskMark();
		UserInfo userInfo = imContext.getBusinessModule().getCacheManager().getUserInfo();
		imContext.getBusinessModule().getServiceWrapper()
				.userPostArticle(this, aTaskMark, userInfo.getUserID(), titleStr, contentStr, imgs, category);

		dialog.show();
	}

	private void updateAddPostImgLayout() {
		if (viewHolders.size() == 0) {
			int count = addpostImgLayout.getChildCount();
			for (int i = 0; i < count; i++) {
				ViewGroup viewGroup = (ViewGroup) addpostImgLayout.getChildAt(i);
				int cCount = viewGroup.getChildCount();
				for (int j = 0; j < cCount; j++) {
					View view = viewGroup.getChildAt(j);
					ViewHolder viewHolder = new ViewHolder(view);
					viewHolders.add(viewHolder);
				}
			}
		}

		int imgSize = imgs.size();
		int viewSize = viewHolders.size();
		for (int i = 0; i < imgSize; i++) {
			viewHolders.get(i).addImageLayout.setVisibility(View.VISIBLE);
			viewHolders.get(i).addImage.setTag(imgs.get(i));
			if (imgs.get(i).startsWith(ContentResolver.SCHEME_CONTENT)) {
				Picasso.with(imContext).load(imgs.get(i)).centerCrop()
						.resizeDimen(R.dimen.addpost_img_size, R.dimen.addpost_img_size)
						.into(viewHolders.get(i).addImage);

			} else {
				Picasso.with(imContext).load(new File(imgs.get(i))).centerCrop()
						.resizeDimen(R.dimen.addpost_img_size, R.dimen.addpost_img_size)
						.into(viewHolders.get(i).addImage);
			}

		}

		if (imgSize >= viewSize) {
			return;
		}

		viewHolders.get(imgSize).addImageLayout.setVisibility(View.VISIBLE);
		viewHolders.get(imgSize).addImage.setImageBitmap(null);
		viewHolders.get(imgSize).addImage.setTag(ADD_POST_BTN);

		for (int i = imgSize + 1; i < viewSize; i++) {
			viewHolders.get(i).addImageLayout.setVisibility(View.INVISIBLE);
		}

	}

	class ViewHolder {

		@Bind(R.id.addImage)
		ImageView addImage;
		@Bind(R.id.addImageLayout)
		FrameLayout addImageLayout;

		public ViewHolder(View view) {
			ButterKnife.bind(this, view);
		}

		@OnClick(R.id.addImage)
		public void onAddImageClick(View view) {
			String tag = (String) view.getTag();
			if (tag.equals(ADD_POST_BTN)) {
				selectPicWindow.show();

			} else {
				if (StringUtil.isEmptyString(tag))
					return;
				imgs.remove(tag);
				if (!tag.startsWith(ContentResolver.SCHEME_CONTENT)) {
					File file = new File(tag);
					file.deleteOnExit();
				}
			}

			updateAddPostImgLayout();
		}

	}

	@OnCheckedChanged(R.id.irrigation)
	public void onIrrigationChecked(boolean checked) {
		if (checked) {
			category = "灌水";
		}

	}

	@OnCheckedChanged(R.id.secondhand)
	public void onSecondhandChecked(boolean checked) {
		if (checked) {
			category = "二手";
		}

	}

	@OnCheckedChanged(R.id.seekhelp)
	public void onSeekhelpChecked(boolean checked) {
		if (checked) {
			category = "求助";
		}

	}

	@Override
	public void onActivityResult(int requestCode, int resultCode, Intent result) {
		if (requestCode == Crop.REQUEST_PICK && resultCode == Activity.RESULT_OK) {
			Uri uri = result.getData();
			String path = AppUtils.createFile(this, uri, FileUtil.getSdcardStoreDir() + File.separator
					+ PhoConstants.ADD_POST_IMAGE_DIR + System.currentTimeMillis() + ".jpg");
			if (!StringUtil.isEmptyString(path)) {
				imgs.add(path);
			}

		} else if (requestCode == Crop.REQUEST_CAMERA && resultCode == Activity.RESULT_OK) {
			imgs.add(localFilePath);
		}

		updateAddPostImgLayout();
	}

	@Override
	public void onClick(View v) {
		switch (v.getId()) {
		/* 从相机获取头像 */
		case R.id.btn_take_photo:
			selectPicWindow.dismiss();
			String state = Environment.getExternalStorageState();
			if (state.equals(Environment.MEDIA_MOUNTED)) {
				String imgDir = FileUtil.getSdcardStoreDir() + File.separator + PhoConstants.ADD_POST_IMAGE_DIR;
				File dir = new File(imgDir);
				if (!dir.exists()) {
					dir.mkdirs();
				}

				localFilePath = imgDir + System.currentTimeMillis() + ".jpg";
				Crop.cameraImage(this, Crop.REQUEST_CAMERA, Uri.fromFile(new File(localFilePath)));

			} else {
				Toast.makeText(getApplicationContext(), R.string.check_sdcard, 200).show();
			}

			break;

		/* 从相册获取图片 */
		case R.id.btn_pick_photo:
			String imgDir = FileUtil.getSdcardStoreDir() + File.separator + PhoConstants.ADD_POST_IMAGE_DIR;
			File dir = new File(imgDir);
			if (!dir.exists()) {
				dir.mkdirs();
			}
			selectPicWindow.dismiss();
			Crop.pickImage(this, Crop.REQUEST_PICK);

			break;
		}
	}

	@Override
	protected void onDestroy() {
		imgs.clear();
		String state = Environment.getExternalStorageState();
		if (state.equals(Environment.MEDIA_MOUNTED)) {
			String imgDir = FileUtil.getSdcardStoreDir() + File.separator + PhoConstants.ADD_POST_IMAGE_DIR;
			FileUtil.delAllChildrenFiles(imgDir);
		}
		dialog.dismiss();

		super.onDestroy();
	}

	@Override
	public void receiveResult(ATaskMark taskMark, ActionException exception, Object trackerResult) {
		if (taskMark instanceof UserPostArticleTaskMark) {
			if (taskMark.getTaskStatus() == ATaskMark.HANDLE_OVER) {
				dialog.hide();
				finish();

			} else if (taskMark.getTaskStatus() == ATaskMark.HANDLE_ERROR) {
				Toast.makeText(this, R.string.report_error, 200).show();
				dialog.hide();
			}

		}
	}

}
